package com.stormrage.xiangyu.plugin;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

import com.stormrage.xiangyu.Constants;
import com.stormrage.xiangyu.XiangyuApplication;
import com.stormrage.xiangyu.view.NewCallActivity;
import com.stormrage.xiangyu.view.VideoCallActivity;
import com.tencent.TIMConversation;
import com.tencent.TIMConversationType;
import com.tencent.TIMGroupAddOpt;
import com.tencent.TIMManager;
import com.tencent.TIMMessage;
import com.tencent.TIMOfflinePushSettings;
import com.tencent.TIMTextElem;
import com.tencent.TIMValueCallBack;
import com.tencent.ilivesdk.ILiveCallBack;
import com.tencent.ilivesdk.ILiveConstants;
import com.tencent.ilivesdk.ILiveSDK;
import com.tencent.ilivesdk.business.callbusiness.ILVCallConfig;
import com.tencent.ilivesdk.business.callbusiness.ILVCallConstants;
import com.tencent.ilivesdk.business.callbusiness.ILVCallListener;
import com.tencent.ilivesdk.business.callbusiness.ILVCallManager;
import com.tencent.ilivesdk.business.callbusiness.ILVCallOption;
import com.tencent.ilivesdk.business.callbusiness.ILVIncomingListener;
import com.tencent.ilivesdk.core.ILiveLoginManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.IOException;

import io.dcloud.application.DCloudApplication;
import io.dcloud.common.DHInterface.IWebview;
import io.dcloud.common.DHInterface.StandardFeature;
import io.dcloud.common.util.BaseInfo;
import io.dcloud.feature.internal.sdk.SDK;

import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;

/**
 * Created by mac on 16/10/27.
 */

public class Xiangyu extends StandardFeature implements ILVIncomingListener,ILVCallListener {


    private String username ;//自己的ID
    private Context context;
    private IWebview iWebview;
    private String oper = "";
    private static Xiangyu xiangyu;

    public void onStart(Context pContext, Bundle pSavedInstanceState, String[] pRuntimeArgs) {

        /**
         * 如果需要在应用启动时进行初始化，可以继承这个方法，并在properties.xml文件的service节点添加扩展插件的注册即可触发onStart方法
         * */
        context = pContext;
        Log.i("xiangyu","onstart");

        // 关闭IM群组
        ILVCallManager.getInstance().init(new ILVCallConfig());

        // 设置通话回调
        ILVCallManager.getInstance().addIncomingListener(this);
        ILVCallManager.getInstance().addCallListener(this);
        this.xiangyu = this;
    }

    public static Xiangyu getInstance(){
        if (xiangyu!=null) {
            return xiangyu;
        }else{
            return new Xiangyu();
        }
    }

    /**
     * 登录腾讯云的方法
     * @param sig 签名
     */
    private void qqLogin(String sig) {
        Log.i("login","准备登陆腾讯云");


        ILiveLoginManager.getInstance().iLiveLogin(username, sig, new ILiveCallBack() {
            @Override
            public void onSuccess(Object data) {
                myNativeToJavascript(1003);
                //开启离线通知
                TIMOfflinePushSettings settings = new TIMOfflinePushSettings();
                settings.setEnabled(true);
                Uri uri = Uri.parse("file:///android_asset/apps/H5C3F08B0_USER/www/audio/call.mp3");
                settings.setC2cMsgRemindSound(uri);
                TIMManager.getInstance().configOfflinePushSettings(settings);
            }

            @Override
            public void onError(String module, int errCode, String errMsg) {
                myNativeToJavascript(1004);
                Log.i("登录","失败:module:"+module+",msg:,"+errMsg+",code:"+errCode);
            }
        });
    }


    /**
     * QQ登陆  这个是给WEBVIEW调用的

     */
    public void txlogin(final IWebview pWebview, JSONArray array){
        this.iWebview = pWebview;
        username = array.optString(0);
        String pass = array.optString(1);
        String nick = array.optString(2);
        RequestParams params = new RequestParams("http://api.51edn.com/");
        params.addBodyParameter("action","getSig");
        params.addBodyParameter("appid",String.valueOf(XiangyuApplication.appid));
        params.addBodyParameter("user",username);
        x.http().post(params, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject result) {
                Log.i("success",result.toString());
                try {
                    myNativeToJavascript(1000);
                    qqLogin(result.getString("sig"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                myNativeToJavascript(1001);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 退出登录
     */
    public void txloginout(final IWebview pWebview, JSONArray array){
        ILiveLoginManager.getInstance().iLiveLogout(new ILiveCallBack() {
            @Override
            public void onSuccess(Object data) {
                Log.i("退出","退出成功");
                myNativeToJavascript(1002);
            }

            @Override
            public void onError(String module, int errCode, String errMsg) {

            }
        });
    }

    /**
     * 这里发一条视频消息
     */
    public void sendVideo(IWebview pWebview, JSONArray array){
        String peerName = array.optString(0);

        if (ILiveLoginManager.getInstance().getMyUserId().equals("")){
            Log.e("腾讯云","未登录");
            myNativeToJavascript(1012);
            return;
        }
        //给对面发一条文本消息  主要是用于苹果版推送不能处理自定义消息
        TIMTextElem textElem = new TIMTextElem();
        textElem.setText("您收到新的视频通话");
        TIMConversation conversation = TIMManager.getInstance().getConversation(TIMConversationType.C2C,peerName);
        TIMMessage msg = new TIMMessage();
        msg.addElement(textElem);
        conversation.sendMessage(msg, new TIMValueCallBack<TIMMessage>() {
            @Override
            public void onError(int i, String s) {
                Log.i("timmessage","消息发送失败:"+i+s);
            }

            @Override
            public void onSuccess(TIMMessage timMessage) {
                Log.i("timmessage","消息发送成功");
            }
        });

        ILVCallOption callOption = new ILVCallOption(ILiveLoginManager.getInstance().getMyUserId()).setCallType(ILVCallConstants.CALL_TYPE_VIDEO);

        String myNick = array.optString(1);
        String myIcon = array.optString(2);
        oper = array.optString(3);
        callOption.customParam(myNick+"<||>"+myIcon);

        Log.i("customParam",callOption.getCustomParam());

        int callId = ILVCallManager.getInstance().makeCall(peerName,callOption);

        if (ILiveConstants.INVALID_INTETER_VALUE != callId){
            // 成功处理
            Intent intent = new Intent();
            intent.setClass(context, VideoCallActivity.class);
            intent.putExtra("HostId", ILiveLoginManager.getInstance().getMyUserId());
            intent.putExtra("CallId", callId);
            intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    }

    //???
    @Override
    public void onCallEstablish(int callId) {

    }

    //通话结束
    @Override
    public void onCallEnd(int callId, int endResult, String endInfo) {

    }

    //异常退出
    @Override
    public void onException(int iExceptionId, int errCode, String errMsg) {

    }

    @Override
    public void onNewIncomingCall(final int callId, int callType, String fromUserId, String strTips, String strCustom, long timeStamp) {
        if (System.currentTimeMillis()/1000 - timeStamp > 5){
            Log.i("新的通话","消息是离线的时候发的 忽略");
            return;
        }

        Log.i("新的通话","callid:"+callId+",calltype:"+callType+",fromuserid:"+fromUserId+",strtips"+strTips+",strcustom"+strCustom);

        Intent intent = new Intent(context,NewCallActivity.class);
        intent.putExtra("callId",callId);
        intent.putExtra("callType",callType);
        intent.putExtra("fromUserId",fromUserId);
        intent.putExtra("strTips",strTips);
        intent.putExtra("strCustom",strCustom);

        String[] strCus = strCustom.split("<\\|\\|>");
        Log.i("strCus","length:"+strCus.length);
        if (strCus.length==2){
            intent.putExtra("nickname",strCus[0]);
            intent.putExtra("iconurl",strCus[1]);
        }

        intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }


    //NATIVE -> JS  通知代码
    //1000    获取用户SIG成功
    //1001    获取用户SIG失败
    //1002    用户注销成功
    //1003    腾讯云登录成功
    //1004    腾讯云登录失败

    //1005    视频通话开始
    //1006    视频通话结束
    //1007    视频通话接受
    //1008    视频通话拒绝
    //1009    发起人取消视频
    //1010    对方不在线或正忙
    //1011    对方正忙
    //1012    用户未登录  不能发起视频
    public void myNativeToJavascript(int i){
        String js = String.format("nativeToJavascript(%s,'%s')",i,oper);
        Log.i("通知js",js);

//        IWebview iWebview = SDK.obatinFirstPage(SDK.obtainCurrentApp());
        this.iWebview.evalJS(js);
    }

    public void sendVideoTime(long i){
        String js = String.format("videoTimeLong(%s,'%s')",i,oper);
        Log.i("时间js",js);
        IWebview iWebview = SDK.obatinFirstPage(SDK.obtainCurrentApp());
        iWebview.evalJS(js);
    }
}
